<template>
  <div class="login-right">
    <div class="register">
      <a href="">
        <svg-icon icon-class="back" />
      </a>
    </div>
    <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" auto-complete="on" label-position="left">
      <div :class="[isRight? 'error-msg transparent': 'error-msg']">
        两次密码输入不一致，请重新输入
      </div>
      <h3 class="title">服务商登录</h3>
      <p class="prompt">欢迎光临！ 请填写用户名和密码登录到您的账户。</p>
      <el-form-item :class="[isRight? '': 'error-border']" prop="email">
        <el-input v-model="loginForm.username" name="username" type="text" placeholder="手机号或邮箱" @blur="handleObtainPubkey" />
      </el-form-item>
      <el-form-item :class="[isRight? '': 'error-border']" prop="password">
        <el-input
          :type="pwdType"
          v-model="loginForm.password"
          name="password"
          placeholder="密码"
          @keyup.enter.native="handleLogin" />
        <span class="show-pwd" @click="showPwd">
          <svg-icon icon-class="eye" />
        </span>
      </el-form-item>
      <div class="forget-password">
        <router-link to="/login/forgetPwd" >
          忘记密码？
        </router-link>
      </div>
      <el-form-item>
        <el-button :loading="loading" type="primary" style="width:100%;" @click.native.prevent="handleLogin">
          立即登录
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { isvalidUsername } from '@/utils/validate'
import md5 from 'md5'
import sha256 from 'js-sha256'
import { mapGetters } from 'vuex'

export default {
  name: 'Login',
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!isvalidUsername(value)) {
        callback(new Error('请输入正确的用户名'))
      } else {
        callback()
      }
    }
    const validatePass = (rule, value, callback) => {
      if (value.length < 5) {
        callback(new Error('密码不能小于5位'))
      } else {
        callback()
      }
    }
    return {
      loginForm: {
        username: '',
        password: '',
        passwordEncrypt: '',
        acc_key: ''
      },
      loginRules: {
        username: [{ required: true, trigger: 'blur', validator: validateUsername }],
        password: [{ required: true, trigger: 'blur', validator: validatePass }]
      },
      isRight: true,
      loading: false,
      pwdType: 'password',
      redirect: undefined
    }
  },
  computed: {
    ...mapGetters([
      'pub_key',
      'acc_key'
    ])
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    }
  },
  methods: {
    showPwd() {
      if (this.pwdType === 'password') {
        this.pwdType = ''
      } else {
        this.pwdType = 'password'
      }
    },
    handleObtainPubkey() {
      this.$store.dispatch('ObtainPubkey', this.loginForm).then(() => {
      })
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          this.encryptPassword(this.loginForm.password, this.pub_key)
          this.loginForm.acc_key = this.acc_key
          this.$store.dispatch('Login', this.loginForm).then((state) => {
            this.loading = false
            switch (state) {
              case 0:
                this.$router.replace({ path: '/register/first' })
                break
              case 1:
                this.$router.replace({ path: '/register/second' })
                break
              case 2:
                this.$router.replace({ path: '/register/third' })
                break
              case 3:
                this.$router.replace({ path: '/register/fourth/failure' })
                break
              case 4:
                this.$router.replace({ path: '/register/fourth/review' })
                break
              case 5:
                this.$router.replace({ path: '/register/fourth/success' })
                break
              case 6:
                this.$router.replace({ path: this.redirect || '/' })
                break
              default:
                this.$router.replace({ path: this.redirect || '/' })
            }
          }).catch(() => {
            this.loading = false
          })
        } else {
          console.log('请填写正确的用户名和密码!')
          return false
        }
      })
    },
    encryptPassword(password, pubkey) {
      this.loginForm.passwordEncrypt = sha256.hmac(pubkey, md5(password))
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
  $pink: #Faa39e;
  $light_orange: rgba(254,241,240,1);
  $red:rgba(244,41,53,1);
  $dark_gray:#889aa4;
  .forget-password {
    text-align: right;
    font-size:14px;
    font-weight:400;
    color:rgba(102,102,102,1);
    line-height:20px;
    margin-top: 2px;
    margin-bottom: 23px;
  }
  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }
  .show-pwd {
    position: absolute;
    right: 10px;
    top: 0;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
  .error-msg {
    width:320px;
    height:28px;
    background: $light_orange;
    border-radius:2px;
    border:1px solid $pink;
    text-align: center;
    line-height: 28px;
    font-size:12px;
    font-family:MicrosoftYaHei;
    color: $red;
  }
  .transparent {
    opacity: 0;
  }
  .error-border {
    border: 1px solid $pink;
  }
</style>

